<template>
	<div class="announcement-board">
		<div v-if="loading" class="home-empty">
			<el-icon class="loading-icon"><Loading /></el-icon>
			<div class="empty-text">加载中...</div>
		</div>

		<div v-else-if="announcements.length === 0" class="home-empty">
			<el-icon class="empty-icon"><BellFilled /></el-icon>
			<div class="empty-text">暂无{{ categoryType ? categoryType + '类' : '' }}通知公告</div>
			<div class="empty-desc">稍后查看最新通知</div>
		</div>

		<div v-else class="announcement-list">
			<div v-for="announcement in announcements" :key="announcement.ID" class="announcement-item" @click="handleAnnouncementClick(announcement)">
				<!-- 简化的公告项 -->
				<div class="announcement-main">
					<!-- 左侧内容 -->
					<div class="announcement-content">
						<!-- 标题和状态 -->
						<div class="title-row">
							<h4 class="announcement-title">
								{{ announcement.Title }}
							</h4>
							<div class="announcement-badges">
								<span v-if="announcement.IsTop" class="priority-badge">重要</span>
								<span v-if="announcement.IsRecommend" class="recommend-badge">推荐</span>
							</div>
						</div>

						<!-- 简化的元信息 -->
						<div class="announcement-meta">
							<span class="publish-time">
								{{ formatSimpleTime(announcement.CreateTime) }}
							</span>
							<span
								v-if="getCategoryInfo(announcement.CategoryName)"
								class="category-info"
								:style="{
									backgroundColor: getCategoryInfo(announcement.CategoryName)?.color + '20',
									color: getCategoryInfo(announcement.CategoryName)?.color,
									borderColor: getCategoryInfo(announcement.CategoryName)?.color + '40',
								}"
							>
								{{ getCategoryInfo(announcement.CategoryName)?.name || announcement.CategoryName }}
							</span>
							<span class="view-count"> {{ announcement.ViewCount || 0 }} 次查看 </span>
						</div>
					</div>

					<!-- 右侧箭头 -->
					<div class="announcement-arrow">
						<el-icon><ArrowRight /></el-icon>
					</div>
				</div>
			</div>
		</div>
		<NewsDetail :row="detailRow" v-model:visible="detailVisible" />
	</div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, defineAsyncComponent } from 'vue';
import { Loading, BellFilled, ArrowRight } from '@element-plus/icons-vue';
import { SysArticleApi } from '/@/views/article/sysarticle/api/index';
import { SysArticleCategoryApi } from '/@/views/article/sysarticlecategory/api/index';
import NewsDetail from './NewsDetail.vue';
import { useArticleStore } from '/@/views/home/composables/useArticleStore';
import { auth } from '/@/utils/authFunction';

/**
 * 组件属性定义
 */
interface Props {
	/** 文章分类类型，用于过滤数据 */
	categoryType?: string;
	/** 是否显示所有分类的数据，默认false */
	showAllCategories?: boolean;
	/** 最大显示数量，默认5 */
	maxCount?: number;
}

const props = withDefaults(defineProps<Props>(), {
	categoryType: '',
	showAllCategories: false,
	maxCount: 5,
});

/**
 * 分类信息结构
 */
interface CategoryInfo {
	icon: string;
	color: string;
	name: string;
	isActive: boolean;
	isVisible: boolean;
}

const emit = defineEmits(['announcement-count']);

// 状态变量
const loading = ref(false);
const announcements = ref<any[]>([]);
const categories = ref<any[]>([]);
const categoryMap = ref<Record<string, CategoryInfo>>({});
const detailVisible = ref(false);
const detailRow = ref<any | null>(null);

// 文章数据管理 - 为每个组件实例创建独立的缓存键
const articleStore = useArticleStore();
const cacheKey = computed(() => `announcements_${props.categoryType || 'all'}_${props.maxCount}`);

// 计算属性

/**
 * 获取分类信息，并验证是否应该显示
 */
function getCategoryInfo(categoryName: string): CategoryInfo | null {
	const category = categoryMap.value[categoryName];
	if (category && category.isActive && category.isVisible) {
		return category;
	}
	return null;
}

/**
 * 根据分类类型过滤文章数据
 */
function filterArticlesByCategory(articles: any[]): any[] {
	if (!props.categoryType || props.showAllCategories) {
		return articles;
	}

	return articles.filter((article) => {
		// 根据分类名称过滤
		if (article.CategoryName === props.categoryType) {
			return true;
		}

		// 根据分类ID过滤（如果有的话）
		if (article.CategoryId && article.Category?.CategoryName === props.categoryType) {
			return true;
		}

		return false;
	});
}

/**
 * 公告点击事件
 */
const handleAnnouncementClick = (announcement: any) => {
	detailRow.value = announcement;
	detailVisible.value = true;
};

/**
 * 格式化时间
 */
function formatTime(timestamp: string): string {
	const date = new Date(timestamp);
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	const hours = String(date.getHours()).padStart(2, '0');
	const minutes = String(date.getMinutes()).padStart(2, '0');
	return `${year}-${month}-${day} ${hours}:${minutes}`;
}

/**
 * 简化的时间格式化 - 只显示日期
 */
function formatSimpleTime(timestamp: string): string {
	const date = new Date(timestamp);
	const now = new Date();
	const diffTime = now.getTime() - date.getTime();
	const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

	if (diffDays === 0) {
		return '今天';
	} else if (diffDays === 1) {
		return '昨天';
	} else if (diffDays < 7) {
		return `${diffDays}天前`;
	} else {
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		return `${month}-${day}`;
	}
}

/**
 * 获取状态类名
 */
function getStatusClass(status: string): string {
	switch (status) {
		case '已发布':
			return 'published';
		case '已撤销':
			return 'revoked';
		case '已删除':
			return 'deleted';
		default:
			return '';
	}
}

/**
 * 加载文章和分类数据
 */
async function loadData() {
	try {
		loading.value = true;

		// 检查权限，如果没有权限则直接返回
		if (!auth('/api/SysArticle/Search')) {
			loading.value = false;
			return;
		}

		// 检查缓存
		if (articleStore.hasCache(cacheKey.value)) {
			const cachedData = articleStore.getCachedArticles(cacheKey.value);
			announcements.value = cachedData;
			loading.value = false;
			emit('announcement-count', announcements.value.length);

			// 检查分类缓存
			if (articleStore.hasCategoryCache()) {
				const cachedCategories = articleStore.getCachedCategories();
				categories.value = cachedCategories;
				updateCategoryMap(cachedCategories);
			} else {
				await loadCategories(); // 只在没有分类缓存时加载
			}
			return;
		}

		// 加载文章数据
		const api = SysArticleApi();

		// 构建查询参数
		const searchParams: any = {
			Status: '已发布',
			Page: 1,
			PageSize: props.maxCount * 2, // 获取更多数据以便过滤
		};

		// 如果有指定分类类型，先通过分类名称找到对应的分类ID
		if (props.categoryType && !props.showAllCategories) {
			// 先加载分类数据（如果还没有加载的话）
			if (categories.value.length === 0) {
				await loadCategories();
			}

			// 通过中文分类名称找到对应的分类ID
			const targetCategory = categories.value.find((cat) => cat.CategoryName === props.categoryType);
			if (targetCategory && targetCategory.ID) {
				searchParams.CategoryId = targetCategory.ID;
				console.log(`[AnnouncementBoard] 找到分类 "${props.categoryType}" 的ID:`, targetCategory.ID);
			} else {
				console.warn(`[AnnouncementBoard] 未找到分类 "${props.categoryType}" 对应的ID`);
			}
		}

		// 调试日志：显示实际发送的查询参数
		console.log(`[AnnouncementBoard] 查询参数:`, {
			categoryType: props.categoryType,
			showAllCategories: props.showAllCategories,
			searchParams: searchParams,
		});

		const res = await api.search(searchParams);
		const data = (res as any).Data || [];

		// 如果后端已经按分类过滤，则不需要再次过滤
		// 否则在前端进行过滤（作为备用方案）
		let filteredData = data;
		if (!searchParams.CategoryName) {
			filteredData = filterArticlesByCategory(data);
		}

		// 排序：置顶 > 推荐 > 创建时间
		announcements.value = filteredData.sort((a: any, b: any) => {
			// 首先按置顶排序
			if (a.IsTop !== b.IsTop) {
				return b.IsTop ? 1 : -1;
			}
			// 然后按推荐排序
			if (a.IsRecommend !== b.IsRecommend) {
				return b.IsRecommend ? 1 : -1;
			}
			// 最后按创建时间排序
			return new Date(b.CreateTime).getTime() - new Date(a.CreateTime).getTime();
		});

		// 限制显示数量
		announcements.value = announcements.value.slice(0, props.maxCount);

		// 缓存数据
		articleStore.cacheArticles(announcements.value, cacheKey.value);

		// 发送公告数量
		emit('announcement-count', announcements.value.length);

		// 加载分类
		await loadCategories();
	} catch (error) {
		console.error('加载公告数据失败:', error);
	} finally {
		loading.value = false;
	}
}

/**
 * 更新分类映射
 */
function updateCategoryMap(categoryData: any[]) {
	categoryMap.value = {};
	categoryData.forEach((cat: any) => {
		categoryMap.value[cat.CategoryName] = {
			icon: cat.Icon,
			color: cat.Color,
			name: cat.CategoryName,
			isActive: cat.IsActive,
			isVisible: cat.IsVisible,
		};
	});
}

/**
 * 加载分类数据
 */
async function loadCategories() {
	// 检查权限，如果没有权限则直接返回
	if (!auth('/api/SysArticleCategory/Search')) {
		return;
	}

	try {
		const categoryApi = SysArticleCategoryApi();
		const categoryRes = await categoryApi.search({ Page: 1, PageSize: 100 });
		const categoryData = (categoryRes as any).Data || [];

		// 更新分类数组
		categories.value = categoryData;

		// 更新分类映射
		updateCategoryMap(categoryData);

		// 缓存分类数据
		articleStore.cacheCategories(categoryData);
	} catch (error) {
		console.error('加载分类数据失败:', error);
	}
}

/**
 * 刷新数据
 */
async function refreshData() {
	// 清除缓存
	articleStore.clearCache(cacheKey.value);
	articleStore.clearCategoryCache();
	// 重新加载数据
	await loadData();
}

// 监听属性变化，重新加载数据
watch(
	() => [props.categoryType, props.maxCount],
	() => {
		refreshData();
	},
	{ immediate: false }
);

// 暴露刷新方法给父组件
defineExpose({
	refresh: refreshData,
});

// 初始化
onMounted(loadData);
</script>

<style scoped>
/* 🎨 现代化简洁设计 */
.announcement-board {
	height: 100%;
	display: flex;
	flex-direction: column;
	min-height: auto;
}

.announcement-list {
	display: flex;
	flex-direction: column;
	gap: 8px;
	flex: 1;
	overflow-y: auto;
	scrollbar-width: thin;
	scrollbar-color: #e1e5e9 transparent;
	padding: 0;
}

/* 滚动条样式 */
.announcement-list::-webkit-scrollbar {
	width: 4px;
}

.announcement-list::-webkit-scrollbar-track {
	background: transparent;
}

.announcement-list::-webkit-scrollbar-thumb {
	background: #e1e5e9;
	border-radius: 2px;
}

.announcement-list::-webkit-scrollbar-thumb:hover {
	background: #c1c7cd;
}

/* 🎯 简化的公告项目 */
.announcement-item {
	background: #ffffff;
	border: 1px solid #f0f2f5;
	border-radius: 8px;
	padding: 16px;
	cursor: pointer;
	transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
	position: relative;
	overflow: hidden;
	min-height: 72px;

	&:hover {
		border-color: #409eff;
		background: #fafbfc;
		transform: translateY(-1px);
		box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
	}

	&:hover .announcement-arrow {
		transform: translateX(4px);
		color: #409eff;
	}

	&:active {
		transform: translateY(0);
	}
}

/* 主要内容布局 */
.announcement-main {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 16px;
}

.announcement-content {
	flex: 1;
	min-width: 0; /* 允许flex子项收缩 */
}

/* 标题行 */
.title-row {
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	gap: 12px;
	margin-bottom: 8px;
}

.announcement-title {
	font-size: 15px;
	font-weight: 600;
	color: #1f2937;
	line-height: 1.4;
	margin: 0;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
	flex: 1;
}

.announcement-badges {
	display: flex;
	align-items: center;
	gap: 6px;
	flex-shrink: 0;
}

/* 简化的徽章样式 */
.priority-badge {
	background: linear-gradient(135deg, #ff6b6b, #ee5a52);
	color: white;
	padding: 2px 8px;
	border-radius: 12px;
	font-size: 11px;
	font-weight: 600;
	white-space: nowrap;
	box-shadow: 0 2px 4px rgba(238, 90, 82, 0.3);
}

.recommend-badge {
	background: linear-gradient(135deg, #51cf66, #40c057);
	color: white;
	padding: 2px 8px;
	border-radius: 12px;
	font-size: 11px;
	font-weight: 600;
	white-space: nowrap;
	box-shadow: 0 2px 4px rgba(64, 192, 87, 0.3);
}

/* 元信息行 */
.announcement-meta {
	display: flex;
	align-items: center;
	gap: 16px;
	font-size: 12px;
	color: #6b7280;
	flex-wrap: wrap;
}

.publish-time {
	color: #6b7280;
	font-weight: 500;
}

.category-info {
	padding: 2px 8px;
	border-radius: 10px;
	font-weight: 500;
	border: 1px solid transparent;
	transition: all 0.2s ease;
	/* 默认样式，会被动态样式覆盖 */
	color: #409eff;
	background: #e7f3ff;
	border-color: #409eff40;
}

.view-count {
	color: #9ca3af;
	font-size: 11px;
}

/* 右侧箭头 */
.announcement-arrow {
	color: #d1d5db;
	font-size: 16px;
	transition: all 0.2s ease;
	flex-shrink: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	width: 24px;
	height: 24px;
	border-radius: 50%;
	background: #f9fafb;
}

/* 加载状态样式 */
.home-empty {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 40px 20px;
	color: #6b7280;
	flex: 1;
	min-height: 200px;
}

.home-empty .empty-icon,
.home-empty .loading-icon {
	font-size: 48px;
	margin-bottom: 16px;
	color: #d1d5db;
}

.home-empty .loading-icon {
	animation: spin 1.2s linear infinite;
}

.home-empty .empty-text {
	font-size: 16px;
	font-weight: 600;
	margin-bottom: 8px;
	color: #374151;
}

.home-empty .empty-desc {
	font-size: 14px;
	color: #9ca3af;
}

@keyframes spin {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}

/* 🎯 响应式设计 */
@media (max-width: 768px) {
	.announcement-item {
		padding: 12px;
		min-height: 64px;
	}

	.title-row {
		flex-direction: column;
		align-items: flex-start;
		gap: 8px;
	}

	.announcement-badges {
		align-self: flex-start;
	}

	.announcement-meta {
		gap: 12px;
		font-size: 11px;
	}

	.announcement-title {
		font-size: 14px;
		-webkit-line-clamp: 2;
		line-clamp: 2;
	}
}

@media (max-width: 480px) {
	.announcement-list {
		gap: 6px;
	}

	.announcement-item {
		padding: 10px;
		min-height: 56px;
	}

	.announcement-main {
		gap: 12px;
	}

	.title-row {
		margin-bottom: 6px;
	}

	.announcement-title {
		font-size: 13px;
		-webkit-line-clamp: 1;
		line-clamp: 1;
	}

	.announcement-meta {
		gap: 8px;
		font-size: 10px;
	}

	.priority-badge,
	.recommend-badge {
		font-size: 10px;
		padding: 1px 6px;
	}

	.category-info {
		font-size: 10px;
		padding: 1px 6px;
	}
}

/* 🎨 深色模式适配 */
@media (prefers-color-scheme: dark) {
	.announcement-item {
		background: #1f2937;
		border-color: #374151;
	}

	.announcement-item:hover {
		background: #111827;
		border-color: #409eff;
	}

	.announcement-title {
		color: #f9fafb;
	}

	.announcement-meta {
		color: #9ca3af;
	}

	.announcement-arrow {
		background: #374151;
		color: #6b7280;
	}

	.home-empty .empty-text {
		color: #f3f4f6;
	}

	/* 深色模式下的分类标签调整 */
	.category-info {
		/* 在深色模式下，动态颜色会自动应用，这里提供后备样式 */
		color: #60a5fa !important;
		background: #1e3a8a20 !important;
		border-color: #1e3a8a40 !important;
	}
}

/* 🎯 无障碍支持 */
@media (prefers-reduced-motion: reduce) {
	.announcement-item,
	.announcement-arrow {
		transition: none;
	}

	.home-empty .loading-icon {
		animation: none;
	}
}
</style>
